package org.digitaldomination.thefinalcountdown;

import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class Countdown extends Activity {

	Button addcountdown;
	ListView list;
	String selected;
	ArrayList<HashMap<String, String>> mylist;
	long test, count_to, count_from;
	String id, title;
	private Handler mHandler = new Handler();
	private final int REFRESH_RATE = 1000;
	final DBAdapter db = new DBAdapter(this);
	String countdownid, dbId;
	Globals globals = new Globals(this);
    private ViewPager awesomePager;
    private static int NUM_AWESOME_VIEWS = 3;
    private Context cxt;
    private AwesomePagerAdapter awesomeAdapter;
    
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
	    cxt = this;
	    awesomeAdapter = new AwesomePagerAdapter();
	    awesomePager = (ViewPager) findViewById(R.id.awesomepager);
	    awesomePager.setAdapter(awesomeAdapter);
		initialize();
	}

	public void initialize() {

		
		mHandler.removeCallbacks(startTimer);
        mHandler.postDelayed(startTimer, 0);
	}

	@Override
	protected void onResume() {
		super.onResume();
	}
	 private class AwesomePagerAdapter extends PagerAdapter implements OnItemClickListener {
		    @Override
         public int getCount() {
                 return NUM_AWESOME_VIEWS;
         }
		    public int getItemPosition(Object object) {
		        return POSITION_NONE;
		    }
         @Override
	 public Object instantiateItem(View collection, int position) {
     		list = (ListView) new ListView(cxt);
    		registerForContextMenu(list);
    		list.setOnItemClickListener(this);
 		db.open();
		Cursor c = db.querygetcountdowns(++position);
		if(c != null){
			mylist = new ArrayList<HashMap<String, String>>();
			HashMap<String, String> results = new HashMap<String, String>();
			if  (c.moveToFirst()) {
				do {
					id = c.getString(c.getColumnIndex("_id"));
					title = c.getString(c.getColumnIndex("title"));
					count_to = c.getLong(c.getColumnIndex("date_to"));
					count_from = c.getLong(c.getColumnIndex("date_from"));
					int count_type = c.getInt(c.getColumnIndex("count_type"));
					results.put("id", id);
					results.put("title", title);
					switch(count_type)
					{
						case 1:
							results.put("countdown", globals.writetime(count_to));
						break;
						case 2:
							results.put("countdown", globals.writetime(count_from));
						break;
						case 3:
							results.put("countdown", globals.writeprogress(count_to, count_from));
						break;
					}
					mylist.add(results);
					results = new HashMap<String, String>();

				}while (c.moveToNext());

				}
			SimpleAdapter mSchedule = new SimpleAdapter(cxt, mylist, R.layout.listview,
		            new String[] {"id", "title", "countdown"}, new int[] {R.id.id, R.id.title, R.id.countdown});
					list.setAdapter(mSchedule);
			        ((ViewPager) collection).addView(list,0);
			}
		db.close();

        
        return list;
	 }

    @Override
    public void destroyItem(View collection, int position, Object view) {
            ((ViewPager) collection).removeView((ListView) view);
    }

    
    
    @Override
    public boolean isViewFromObject(View view, Object object) {
            return view==((ListView)object);
    }

    
/**
 * Called when the a change in the shown pages has been completed.  At this
 * point you must ensure that all of the pages have actually been added or
 * removed from the container as appropriate.
 * @param container The containing View which is displaying this adapter's
 * page views.
 */
    @Override
    public void finishUpdate(View arg0) {}
    

    @Override
    public void restoreState(Parcelable arg0, ClassLoader arg1) {}

    @Override
    public Parcelable saveState() {
            return null;
    }

    @Override
    public void startUpdate(View arg0) {}
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		
		dbId = ((TextView) arg1.findViewById(R.id.id)).getText().toString();		
		Intent singlecountIntent = new Intent(Countdown.this, Singlecountdown.class);
		singlecountIntent.putExtra("dbId", dbId);
		startActivity(singlecountIntent);
	}
}


	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater mi = getMenuInflater();
		mi.inflate(R.menu.list_menu_item_longpress, menu);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case R.id.menu_edit:
			Toast.makeText(this, "Rediger!!", Toast.LENGTH_SHORT).show();
			break;
		case R.id.menu_delete:
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
			countdownid = ((TextView) info.targetView.findViewById(R.id.id)).getText().toString();
			db.open();
			db.deletecountdown(Long.parseLong(countdownid));
			db.close();

		return true;
		}
		return super.onContextItemSelected(item);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		
		MenuInflater awesome = getMenuInflater();
		awesome.inflate(R.menu.list_menu, menu);		
		
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()){
		case R.id.menu_insert :
			Intent addcountdown = new Intent(Countdown.this, Addcountdown.class);
			startActivity(addcountdown);
			break;
		}
		
		return false;
	}
	private Runnable startTimer = new Runnable() {
	 	   public void run() {
	 		  awesomeAdapter.notifyDataSetChanged();
	 		   mHandler.postDelayed(this,REFRESH_RATE);
	 	   }
	 };


	@Override
	protected void onDestroy() {
		super.onDestroy();
		mHandler.removeCallbacks(startTimer);
	}

	 
	 

}